# -*- coding: utf-8 -*-

from os.path import join, exists
from os import unlink, getpid, unlink

class ExclusiveEror(Exception):
    pass

class Pidder(object):
    """Сам ты пидор"""

    def __init__(self, root = None):
        if not root:
            try:
                from django.conf import settings
                root = settings.RUN_ROOT
            except:
                pass

        if not root:
            raise Exception("Can't detect pid-files directory. Please, read manual")

        self.RUN_ROOT = root

        if not hasattr(self, 'SCRIPT_NAME'):
            raise Exception("SCRIPT_NAME must be defined before using pidder class!")
        
        
        self.PID_FILE = None
        
        pid_file = join(self.RUN_ROOT, '%s.pid' % self.SCRIPT_NAME)
        if exists(pid_file):
            try:
                pid = int(file(pid_file).read())
            except:
                pid = None

            if pid:
                # есть pid-файл. Проверяем активность
                if exists('/proc/%d' % getpid()):
                    # /proc подключен, я там есть. Проверим pid-файл
                    if exists('/proc/%d' % pid):
                        raise ExclusiveEror("Another copy of %s already running on pid %s (pid-file - %s)" % (self.SCRIPT_NAME, pid, pid_file))
                    else:
                        #print "Stale pid-file found. Removing"
                        unlink(pid_file)
                    
        else:
            pass
        
        self.PID_FILE = pid_file
        f = file(pid_file, 'w')
        f.write(str(getpid()))
        f.close()


    def release(self):
        if self.PID_FILE:
            if exists(self.PID_FILE):
                unlink(self.PID_FILE)
            self.PID_FILE = None
        
            
    def __del__(self):
        self.release()
        
